package com.pingan.haofang.searchcloud.common.validator;

import com.pingan.haofang.framework.common.functional.lang.control.validator.bo.ValidationError;
import com.pingan.haofang.framework.common.functional.lang.control.validator.bo.ValidationResult;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

/**
 * 校验器工具类
 *
 * @author BAOJIE371
 * @date 2017/2/28
 * @since 1.0.0
 */
public final class ValidatorSupport {

    /**
     * 校验起始、结束日期是否合法
     *
     * @param result
     * @param beginDate
     * @param endDate
     * @param maxBetween
     * @param errorMsg
     */
    public static void validDateBetween(ValidationResult result, Date beginDate, Date endDate,
                                        int maxBetween, String errorMsg) {

        LocalDate beginLocalDate = beginDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        long between = endLocalDate.toEpochDay() - beginLocalDate.toEpochDay() + 1;
        if (between > maxBetween) {
            result.addError(ValidationError.of("endDate", errorMsg, maxBetween)
                    .invalidValue(endDate));
        }
    }

    /**
     * 校验起始、结束月份是否合法
     *
     * @param result
     * @param beginDate
     * @param endDate
     * @param maxBetween
     * @param errorMsg
     */
    public static void validMonthBetween(ValidationResult result, Date beginDate, Date endDate,
                                         int maxBetween, String errorMsg) {

        LocalDate beginLocalMonth = beginDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endLocalMonth = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        int between = (endLocalMonth.getYear() - beginLocalMonth.getYear()) * 12
                + (endLocalMonth.getMonthValue() - beginLocalMonth.getMonthValue());

        if (between > maxBetween) {
            result.addError(ValidationError.of("endDate", errorMsg, maxBetween)
                    .invalidValue(endDate));
        }
    }
}

